package com.zwh.se.common.audio;

import javax.sound.sampled.*;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * @author yexi
 * 音频系统
 */
public class AudioDemo1 {
    public static void main(String[] args) throws URISyntaxException {
        String fileName = "audio/c_1012 00001.wav.wav";
        URL resourceURL = AudioDemo1.class.getClassLoader().getResource(fileName);
        File file = new File(resourceURL.toURI());
        byte[] buffer = new byte[1024 * 1024 * 15];
        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(resourceURL);
        ) {
            AudioFormat audioFormat = audioInputStream.getFormat();
            DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
            try (SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo)) {
                for (int i = 1; i <= 2; i++) {
                    System.out.println("现在播放第" + i + "遍");
                    int len = 0;
                    sourceDataLine.open(audioFormat, 1024 * 1024 * 15);
                    sourceDataLine.start();
                    audioInputStream.mark((int) file.length());

                    while ((len = audioInputStream.read(buffer)) > 0) {
                        sourceDataLine.write(buffer, 0, len);
                    }
                    audioInputStream.reset();
                    sourceDataLine.drain();
                    sourceDataLine.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
